package net.gdface.utils;

import java.util.Iterator;
import java.util.ServiceLoader;

public class SPIUtils {

	private SPIUtils() {
	}
	/**
	 * SPI(Service Provider Interface)机制加载接口实例实例,
	 * 没有找到返回默认实例
	 * @param interfaceClass 接口类
	 * @param defaultInstance 
	 * @return T instance
	 */
	public static <T>T loadProvider(Class<T> interfaceClass,T defaultInstance) {
		Assert.notNull(interfaceClass, "interfaceClass");
		Iterator<T> itor = serviceLoaderOf(interfaceClass).iterator();
		if(!itor.hasNext()){
			return defaultInstance;
		}
		return itor.next();
	}
	/**
	 * 优先调用{@link ServiceLoader#load(Class)},如果返回为空则调用{@link ServiceLoader#load(Class, ClassLoader)}
	 * @param <T>
	 * @param service
	 * @since 2.8.6
	 */
	public static <T> ServiceLoader<T> serviceLoaderOf(Class<T> service){
		ServiceLoader<T> loader = ServiceLoader.load(service);
		return loader.iterator().hasNext() ? loader : ServiceLoader.load(service,service.getClassLoader());
	}
}
